<template>
  <div class="tob">
    <!--搜索-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="用户信息搜索:" prop="condition">
        <el-input
          v-model="condition"
          class="input"
          placeholder="请输入手机号"
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
        <el-button
          icon="el-icon-circle-plus-outline"
          type="success"
          size="mini"
          @click="handleAdd"
        >新增用户</el-button>
        <el-popover
          v-model="visible"
          class="delete"
          placement="top"
          width="160"
        >
          <p>确定删以下用户吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button
              size="mini"
              type="text"
              @click="visible = false"
            >取消</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="handleBatchDel"
            >确定</el-button>
          </div>
          <el-button
            slot="reference"
            icon="el-icon-delete"
            type="danger"
            size="mini"
          >批量删除
          </el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <!--table表格-->
    <template>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 90%"
        @selection-change="selsChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="头像" width="80">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="40" height="40">
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="nickName" label="昵称" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="gender" label="性别">
          <template slot-scope="scope">
            {{ scope.row.gender === 1 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleUpdate(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="text"
              size="small"
              @click="examine(scope.row.id)"
            >查看认证</el-button>
            <el-button
              type="text"
              size="small"
              @click="authorization(scope.row.id)"
            >授权</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--分页-->
    <template>
      <el-row style="height: 60px" justify="end" class="middle">
        <el-pagination
          :page-size="pageParams.pageSize"
          :current-page="pageParams.currentPage"
          :total="pageParams.resultCount"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,prev, pager, next,jumper"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </template>
    <!-- 控制用户新增和编辑弹窗 -->
    <el-dialog
      width="500px"
      :title="title"
      :visible.sync="open"
      @close="closeDialog"
    >
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="form.nickName"
            size="small"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="form.realName"
            size="small"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="form.mobile"
            size="small"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            size="small"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model.number="form.gender" placeholder="请选择性别">
            <el-option
              v-for="option in roleTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input
            v-model="form.department"
            size="small"
            placeholder="请输入部门"
          />
        </el-form-item>
        <el-form-item label="员工头像">
          <!-- 放置上传图片 -->
          <image-upload v-model="form.avatar" />
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="submitForm"
          >确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 授权弹窗 -->
    <el-dialog :visible.sync="show" :title="text">
      <!-- 放置资源数据 -->
      <el-tree
        ref="permTree"
        check-strictly
        node-key="id"
        :data="tabList"
        :props="{ label: 'type' }"
        show-checkbox
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="show = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 电工信息图片 -->
    <el-dialog width="700px" :visible.sync="ensconce" :title="title">
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%;"
        :src="imageList1"
      />
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList2"
      />
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList3"
      />
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList4"
      />
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList5"
      />
      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList6"
      />

      <el-image
        class="aa"
        style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
        :src="imageList7"
      />

    </el-dialog>
  </div>
</template>
<script>
import {
  listRole,
  addRole,
  getRole,
  updateRole,
  deleteRole,
  listRoleAPI,
  authorizationAPI,
  examineAPI
} from '@/api/business/cooperation'
import ImageUpload from './components/image-upload.vue'

export default {
  components: { ImageUpload },
  data() {
    return {
      checkedCities: {},
      // 控制弹出层的显示和隐藏
      visible: false,
      open: false,
      conceal: false,
      ensconce: false,
      value: true,
      // 授权弹窗
      show: false,
      title: '',
      text: '',
      // 批量删除
      sels: [],
      // 模糊查询功能
      condition: '',
      // 分页数据
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        resultCount: 0
      },
      paging: {
        currentPage: 1,
        pageSize: 10,
        resultCount: 0
      },
      imageList1: '',
      imageList2: '',
      imageList3: '',
      imageList4: '',
      imageList5: '',
      imageList6: '',
      imageList7: '',
      // 数据范围选项
      roleTypeOptions: [
        {
          value: 1,
          label: '男'
        },
        {
          value: 0,
          label: '女'
        }
      ],
      // 新增数据
      form: {},
      rules: {
        nickName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        // avatar: [
        //   { required: true, message: '头像不能为空', trigger: 'blur' }
        // ],
        realName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1\d{10}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }
        ],

        department: [
          { required: true, message: '所属部门不能为空', trigger: 'blur' }
        ],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }]
      },
      // 渲染数据
      tableData: [],
      tabList: [],
      // 授权数据
      roleIdData: {},
      roleId: {},
      permIds: {},
      userId: '',
      timer: null // 定时器，用于实现模糊查询时的延迟搜索效果
    }
  },

  created() {
    this.getList()
    // this.getData()
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 新增弹窗
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户'
    },
    // 数据渲染
    async getList() {
      try {
        const res = await listRole(
          this.condition,
          this.pageParams.currentPage,
          this.pageParams.pageSize
        )
        console.log(res)
        this.tableData = res.data
        this.pageParams.currentPage = res.currentPage
        this.pageParams.pageSize = res.pageSize
        this.pageParams.resultCount = res.resultCount
      } catch (error) {
        console.error(error)
        // 处理错误，例如给用户提示错误信息
      }
    },
    // 分页变化时的处理函数
    handleCurrentChange(page) {
      this.pageParams.currentPage = page
      this.getList()
    },
    //   //确认按钮
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            // 确认编辑
            updateRole(this.form).then((response) => {
              this.$message.success('修改用户信息成功')
              this.pageParams.currentPage = 1
              this.open = false // 关闭弹层
              this.getList() // 刷新页面数据
            })
          } else {
            // 新增员工信息逻辑
            addRole(this.form).then((response) => {
              this.$message.success('新增用户信息成功')
              this.pageParams.currentPage = 1
              this.open = false // 关闭弹层
              this.getList() // 刷新页面数据
            })
          }
        }
      })
    },
    // 取消新增功能
    reset() {
      this.form = {
        nickName: '',
        realName: '',
        avatar: '',
        mobile: '',
        email: '',
        gender: '',
        department: ''
        // 表单验证
      }
    },
    closeDialog() {
      // 关闭弹窗前重置表单验证状态
      this.$refs.form.resetFields()
      this.open = false
      // 其他关闭弹窗的逻辑代码...
    },
    // 重置
    resetQuery() {
      this.condition = ''
      this.handleQuery()
    },
    // 搜索功能
    handleQuery() {
      this.pageParams.currentPage = 1
      this.getList()
    },
    // 用户列表编辑功能
    async handleUpdate(id) {
      this.title = '编辑用户'
      const res = await getRole(id)
      this.form = res
      this.open = true
    },

    // 批量删除勾选存储数据
    selsChange(row) {
      this.sels = [...row]
    },
    // 批量删除
    async handleBatchDel() {
      const idsAsString = this.sels.map((item) => item.id.toString())
      try {
        await deleteRole(idsAsString)
        this.$message('删除成功')
        this.visible = false
        this.getList()
      } catch (error) {
        console.error(error)
        this.$message.error('删除失败')
      }
    },
    // 获取授权信息
    // 获取授权信息
    // 获取授权信息
    // 获取授权信息
    // 获取授权信息
    // 获取授权信息
    // async getData() {
    //   try {
    //     console.log(res)
    //     this.$nextTick(() => {

    //     })
    //   } catch (error) {
    //     // 处理错误，例如给用户提示错误信息
    //   }
    // },
    async authorization(id) {
      console.log(id)
      const res = await listRoleAPI(
        this.condition,
        this.pageParams.currentPage,
        this.pageParams.pageSize
      )
      console.log(res, '授权')
      this.tabList = res.data
      this.roleIdData = id
      const ref = await getRole(id)
      this.permIds = ref.id.split(',')
      this.text = '用户授权'
      this.show = true
    },
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    // 查看电工信息
    async examine(id) {
      this.ensconce = true
      this.title = '认证图片'
      console.log(id, '查看')
      const res = await examineAPI(id)
      console.log(res)
      this.imageList1 = res.idCardFrontFileUrl
      this.imageList2 = res.idCardBackFileUrl
      this.imageList3 = res.workerCertFrontFileUrl
      this.imageList4 = res.workerCertBackFileUrl
      this.imageList5 = res.driverLicenseFrontFileUrl
      this.imageList6 = res.driverLicenseBackFileUrl
      this.imageList7 = res.carFrontFileUrl
      console.log(res)
    },
    async btnPermissionOK() {
      const tree = this.$refs.permTree
      const checkedKeys = tree.getCheckedKeys()
      const roleId = []
      for (const key of checkedKeys) {
        roleId.push(String(key)) // 将角色ID添加到数组中
      }
      await authorizationAPI({
        id: this.roleIdData,
        roleId: roleId.join(',') // 将角色ID数组转换为逗号分隔的字符串
      })
      this.$message.success('授权成功')
      this.show = false
    }
    // async accredit() {
    //   const res = await authorizationAPI(this.roleIdData)
    //   console.log(res)
    // }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.aa{
  border: 1px solid #414339;
  margin-right: 5px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #000;
}
.vv {
  margin-top: 10px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.tob {
  width: 100vw;
  height: 100vh;
}

// 搜索框
.demo-form-inline {
  margin: 20px;
}

.input {
  width: 300px;
  margin-right: 30px;
}

.paging {
  text-align: center;
  margin-top: 20px;
}

.middle {
  text-align: center;
  margin-top: 30px;
}

.delete {
  margin-left: 10px;
}
</style>
